package com.example.screenplayer;

import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.nio.ByteBuffer;
import android.os.Handler;
import android.os.Looper;

public class ScreenSocketClient extends WebSocketClient {
private static final String TAG = ScreenSocketClient.class.getSimpleName();
private final SocketCallback mSocketCallback;

private int retryCount = 0;  // 重试次数
private static final int MAX_RETRIES = 5;  // 最大重试次数
private static final long RECONNECT_DELAY = 2000;  // 重连延迟时间（单位：毫秒）

public ScreenSocketClient(SocketCallback socketCallback, URI serverUri) {
  super(serverUri);
  mSocketCallback = socketCallback;
}

@Override
public void onOpen(ServerHandshake serverHandshake) {
  Log.d(TAG, "onOpen");
  retryCount = 0;  // 重置重试次数
}

@Override
public void onMessage(String message) {
  // 处理文本消息
}

@Override
public void onMessage(ByteBuffer bytes) {
  byte[] buf = new byte[bytes.remaining()];
  bytes.get(buf);
  if (mSocketCallback != null) {
    mSocketCallback.onReceiveData(buf);
  }
}

@Override
public void onClose(int code, String reason, boolean remote) {
  Log.d(TAG, "onClose =" + reason);
  // 连接关闭时的处理
}

@Override
public void onError(Exception ex) {
  Log.d(TAG, "onError =" + ex.toString());

  // 判断连接是否处于关闭状态，如果是则重新连接
  if (!isOpen()) {
    try {
      // 判断是否超过最大重试次数
      if (retryCount < MAX_RETRIES) {
        retryCount++;
        Log.d(TAG, "Reconnecting attempt " + retryCount + "...");
        reconnectWithDelay(RECONNECT_DELAY);
      } else {
        Log.e(TAG, "Max reconnect attempts reached");
      }
    } catch (Exception e) {
      Log.e(TAG, "Reconnect failed: " + e.toString());
    }
  }
}

// 重新连接方法，使用延迟重试
private void reconnectWithDelay(long delayMillis) {
  new Handler(Looper.getMainLooper()).postDelayed(() -> {
    if (getReadyState() == ReadyState.CLOSED || getReadyState() == ReadyState.CLOSING) {
      Log.d(TAG, "Reconnecting...");
      // 创建一个新的 WebSocketClient 实例
      ScreenSocketClient newClient = new ScreenSocketClient(mSocketCallback, getURI());
      newClient.connect();  // 连接新的 WebSocketClient
    }
  }, delayMillis);
}

// 开始连接
public void start() {
  if (!isOpen()) {
    this.connect();
  }
}

// 停止连接
public void stop() {
  if (this.isOpen()) {
    this.close();
  }
}

public interface SocketCallback {
  void onReceiveData(byte[] data);
}
}
